package com.cloudy.core.thrift.zookeeper.server;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;


/**
 * 注册服务列表到Zookeeper
 *  基于zookeeper服务地址自动发现实现
 */
public class ThriftServerAddressRegisterZookeeper implements ThriftServerAddressRegister {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private CuratorFramework zkClient;

    public ThriftServerAddressRegisterZookeeper() {
    }

    @Override
    public void register(String service, String version, String address) {
        if (zkClient.getState() == CuratorFrameworkState.LATENT) {
            zkClient.start();
        }
        if (StringUtils.isEmpty(version)) {
            version = "1.0.0";
        }
        //临时节点
        String path = "/" + service + "/" + version + "/" + address;
        try {
             zkClient.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .forPath(path);
//            System.out.println();
        } catch (UnsupportedEncodingException e) {
            logger.error("register service address to zookeeper exception:{}", e);
        } catch (Exception e) {
            logger.error("register service address to zookeeper exception:{}", e);
        }
    }

    public void close() {
        zkClient.close();
    }


    public void setZkClient(CuratorFramework zkClient) {
        this.zkClient = zkClient;
    }
}
